package cn.com.nes.site.module.dao.inventory;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionStatus;

import cn.com.nes.site.entity.DataReq;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.module.dao.BaseDaoImpl;
import cn.com.nes.site.module.dao.UserDaoImpl;

@Repository
public class InventoryDaoImpl  extends BaseDaoImpl{
	private TransactionStatus newg_status = null;
	@Resource
	private UserDaoImpl userDaoImpl;
	//每日晚间自动汇总
	//调用更新
	//传入    orderType  uuid   
//	public PageData changeInventory(DataReq req) {
//		Map<String, Object> param = req.getReqData();
//		String orderType=(String)param.get("orderType");
//		String orderId=(String)param.get("orderId");
		
	public PageData changeInventory(String orderType ,String orderId,String isReturn) {

		PageData res = new PageData();
		StringBuffer sb = new StringBuffer();
		String  tablename="";
		try {
			//入库
			if(orderType!=null && ("01".equals(orderType) || "02".equals(orderType) )){
				tablename="g_order_in";
			}
			//出库
            if(orderType!=null && ("03".equals(orderType) || "04".equals(orderType) )){
            	tablename="g_order_out";
			}
            
            sb.delete(0, sb.length()) ;
			sb.append("SELECT a.uuid, a.orderId, a.serial, a.orderType, a.companyId,  a.goodsUUid, b.goodsCode, b.goodsName, a.inoutNum,  a.warehouseId, c.warehouseName, a.warehouseKeeperID, a.warehouseTime, a.isReturn,b.packingSize,b.unit ") ;
			sb.append(" from ").append(tablename).append(" a ,g_goods b,g_warehouse c ") ;
			sb.append("  where a.goodsUUid=b.uuid and a.warehouseId=c.warehouseId and a.isdelete='0' and a.orderId='").append(orderId).append("'  ");
			if("1".equals(isReturn)) {
				sb.append(" and a.isReturn='1' ");
			}
			List<Map<String, Object>> list = this.getJdbcTemplate_newg()
					.queryForList(sb.toString());
			
			
			//01-采购入库 
			if(orderType!=null && ("01".equals(orderType)  )){
				if (list.size()>0){
					for(int i=0;i<list.size();i++){
						String goodsId=(String)list.get(i).get("goodsUUid");
						sb.delete(0, sb.length()) ;
						sb.append(" select count(*) cnt from g_account where isNew='1' and goodsID= '").append(goodsId).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and  companyId='").append((String)list.get(i).get("companyId")).append("'");
						List<Map<String, Object>> aaa = this.getJdbcTemplate_newg()
								.queryForList(sb.toString());
						if ((Long)aaa.get(0).get("cnt")>0){
							sb.delete(0, sb.length()) ;
							sb.append("update g_account set purchaseNum=purchaseNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(",endingNum=endingNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(" ") ;
							sb.append("  where isNew='1' and goodsID= '").append((String)list.get(i).get("goodsUUid")).append("'   and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and   companyId='").append((String)list.get(i).get("companyId")).append("'");
						}else{
							sb.delete(0, sb.length()) ;
							sb.append(" insert into g_account (uuid,goodsID,goodsName,businessDate,packingSize,unit,initialNum,purchaseNum," +
									" saleNum,customerReturnNum,inventoryAdjustmentNum, "+
									"endingNum,createUid,createTime,goodsCode,companyId,warehouseId,warehouseName,isNew)  ") ;
							sb.append(" values('" +UUID.randomUUID()+
									"','" +Objects.toString((String)list.get(i).get("goodsUUid"),"") +
									"','" +Objects.toString((String)list.get(i).get("goodsName"),"") +
									"',now(),'" +Objects.toString((String)list.get(i).get("packingSize"),"") +
									"','" +Objects.toString((String)list.get(i).get("unit"),"") +
									"',0," +Objects.toString((BigDecimal)list.get(i).get("inoutNum"),"") +
									",0,0,0," +Objects.toString((BigDecimal)list.get(i).get("inoutNum"),"") +
									",'" +Objects.toString((String)list.get(i).get("warehouseKeeperID"),"") +
									"',now(),'" +Objects.toString((String)list.get(i).get("goodsCode"),"") +
									"','" +Objects.toString((String)list.get(i).get("companyId"),"") +
									"','" +Objects.toString((String)list.get(i).get("warehouseId"),"") +
									"','" +Objects.toString((String)list.get(i).get("warehouseName"),"") +
									"','1' ); ");
						}
						this.getJdbcTemplate_newg().update(sb.toString());
					}
					res.setRetCode(0);
					res.setRetMessage("OK");
				}
			}
			// 02-退货入库
			if(orderType!=null && ("02".equals(orderType)  )){
				if (list.size()>0){
					for(int i=0;i<list.size();i++){
						String goodsId=(String)list.get(i).get("goodsUUid");
						sb.delete(0, sb.length()) ;
						sb.append(" select count(*) cnt from g_account where isNew='1' and goodsID= '").append(goodsId).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and  companyId='").append((String)list.get(i).get("companyId")).append("'");
						List<Map<String, Object>> aaa = this.getJdbcTemplate_newg()
								.queryForList(sb.toString());
						if ((Long)aaa.get(0).get("cnt")>0){
							sb.delete(0, sb.length()) ;
							sb.append("update g_account set customerReturnNum=customerReturnNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(",endingNum=endingNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(" ") ;
							sb.append("  where isNew='1' and goodsID= '").append((String)list.get(i).get("goodsUUid")).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("'  and  companyId='").append((String)list.get(i).get("companyId")).append("'");
						}else{
							sb.delete(0, sb.length()) ;
							sb.append(" insert into g_account (uuid,goodsID,goodsName,businessDate,packingSize,unit,initialNum,purchaseNum," +
									" saleNum,customerReturnNum,inventoryAdjustmentNum, "+
									" endingNum,createUid,createTime,goodsCode,companyId,warehouseId,warehouseName,isNew)  ") ;
							sb.append(" values('" +UUID.randomUUID()+
									"','" +Objects.toString((String)list.get(i).get("goodsUUid"),"")+
									"','" +Objects.toString((String)list.get(i).get("goodsName"),"")+
									"',now(), '" +Objects.toString((String)list.get(i).get("packingSize"),"")+
									"','" +Objects.toString((String)list.get(i).get("unit"),"")+
									"',0,0,0," +Objects.toString((BigDecimal)list.get(i).get("inoutNum"),"")+
									",0," +Objects.toString((BigDecimal)list.get(i).get("inoutNum"),"")+
									",'" +Objects.toString((String)list.get(i).get("warehouseKeeperID"),"")+
									"',now(),'" +Objects.toString((String)list.get(i).get("goodsCode"),"")+
									"','" +Objects.toString((String)list.get(i).get("companyId"),"")+
									"','" +Objects.toString((String)list.get(i).get("warehouseId"),"")+
									"','" +Objects.toString((String)list.get(i).get("warehouseName"),"")+
									"','1' ); ");
						}
						this.getJdbcTemplate_newg().update(sb.toString());
					}
					
				}
			}
			//03-销售出库 
			if(orderType!=null && ("03".equals(orderType)  )){
				
				if (list.size()>0){
					//判断库存是否充足
//					for(int i=0;i<list.size();i++){
//						String goodsId=(String)list.get(i).get("goodsUUid");
//						sb.delete(0, sb.length()) ;
//						sb.append(" select count(*) cnt,sum(endingNum) endingNum from g_account where isNew='1' and goodsID= '").append(goodsId).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and  companyId='").append((String)list.get(i).get("companyId")).append("'");
//						List<Map<String, Object>> aaa = this.getJdbcTemplate_newg()
//								.queryForList(sb.toString());
//						if ((Long)aaa.get(0).get("cnt")<=0 ||  ((BigDecimal)aaa.get(0).get("endingNum")).compareTo((BigDecimal)list.get(i).get("inoutNum"))<0){
//							res.setRetCode(1);
//							res.setRetMessage("商品:"+(String)list.get(i).get("goodsName")+"库存不足！");
//							return res;
//						}
//					}
				//出库
				
					for(int i=0;i<list.size();i++){
							sb.delete(0, sb.length()) ;
							sb.append("update g_account set saleNum=saleNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(",endingNum=endingNum-").append((BigDecimal)list.get(i).get("inoutNum")).append(" ") ;
							sb.append("  where isNew='1' and goodsID= '").append((String)list.get(i).get("goodsUUid")).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("'  and  companyId='").append((String)list.get(i).get("companyId")).append("' ");
							this.getJdbcTemplate_newg().update(sb.toString());
					}
				}
			}
			
			//04-损耗出库'
			if(orderType!=null && ("04".equals(orderType)  )){
				
				if (list.size()>0){
					//判断库存是否充足
//					for(int i=0;i<list.size();i++){
//						sb.delete(0, sb.length()) ;
//						sb.append(" select count(*) cnt,sum(endingNum) endingNum from g_account where isNew='1' and goodsID= '").append((String)list.get(i).get("goodsUUid")).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and  companyId='").append((String)list.get(i).get("companyId")).append("'");
//						List<Map<String, Object>> aaa = this.getJdbcTemplate_newg()
//								.queryForList(sb.toString());
//						if ((Long)aaa.get(0).get("cnt")<=0 || ((BigDecimal)aaa.get(0).get("endingNum")).compareTo((BigDecimal)list.get(i).get("inoutNum"))<0){
//							res.setRetCode(1);
//							res.setRetMessage("商品:"+(String)list.get(i).get("goodsName")+"库存不足！");
//							return res;
//						}
//					}
					//出库
					for(int i=0;i<list.size();i++){
							sb.delete(0, sb.length()) ;
							sb.append("update g_account set inventoryAdjustmentNum=inventoryAdjustmentNum+").append((BigDecimal)list.get(i).get("inoutNum")).append(",endingNum=endingNum-").append((BigDecimal)list.get(i).get("inoutNum")).append(" ") ;
							sb.append("  where isNew='1' and goodsID= '").append((String)list.get(i).get("goodsUUid")).append("'  and warehouseId= '").append((String)list.get(i).get("warehouseId")).append("' and  companyId='").append((String)list.get(i).get("companyId")).append("' ");
							this.getJdbcTemplate_newg().update(sb.toString());
					}
				}
			}
				
			res.setRetCode(0);
			res.setRetMessage("OK");
			//res.setPage(list);	
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return res;
	}
	
	
	//查询库存数量  
	public PageData CheckWarehouseNum(DataReq req) {
		Map<String, Object> param = req.getReqData();
		String goodsID=(String)param.get("goodsID");
		String companyId=(String)req.getUinfo().getCompanyId();
//	public PageData CheckWarehouseNum(String goodsID,String companyId) {
		
		
		PageData res = new PageData();
		StringBuffer sb = new StringBuffer();

		try {
			sb.delete(0, sb.length()) ;
			sb.append(" select goodsID,endingNum,warehouseId,warehouseName from g_account where isNew='1' and goodsID= '").append(goodsID).append("'  and companyId= '").append(companyId).append("'");
			List<Map<String, Object>> list = this.getJdbcTemplate_newg()
					.queryForList(sb.toString());
			res.setPage(list);	
			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return res;
	}
	
	//定期进行库存自动汇总 
	public PageData inventorySummary() {
		PageData res = new PageData();
		StringBuffer sb = new StringBuffer();
		StringBuffer sbfrom = new StringBuffer();
		String SummaryTime="";
//		if ("day".equals(Globals.InventorySummaryInterval)){
//			
//		}
//		if ("month".equals(Globals.InventorySummaryInterval)){
//			SummaryTime="-01 00:00:00";
//		}
		try {
			//查询isnew=1的作为起初
			sb.delete(0, sb.length()) ;
			sb.append(" update g_account set isNew='2' where isNew='1' ");
			this.getJdbcTemplate_newg().update(sb.toString());
			
			sb.delete(0, sb.length()) ;
			sb.append(" INSERT INTO g_account (uuid, goodsID, goodsName, businessDate, packingSize, unit, initialNum, initialCost, purchaseNum, purchaseMoney, saleNum, saleMoney, customerReturnNum, customerReturnMoney, companyReturnNum, companyReturnMoney, inventoryCheckNum, inventoryCheckMoney, inventoryAdjustmentNum, inventoryAdjustmentMoney, OutboundNum, OutboundMoney, endingNum, endingMoney, createUid, createTime, goodsCode, companyId, warehouseId, warehouseName, isNew)  ");
			sb.append(" SELECT UUID(), goodsID, goodsName, date_format(now(), '%Y-%m-%d 00:00:00' ), packingSize, unit, endingNum, endingMoney, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, endingNum, endingMoney, 'autoSummary', now(), goodsCode, companyId, warehouseId, warehouseName, '1' ");
			sb.append(" from g_account b ");
			sb.append(" where b.isNew='2' ");
			this.getJdbcTemplate_newg().update(sb.toString());
			
			sb.delete(0, sb.length()) ;
			sb.append(" update g_account set isNew='0' where isNew='2' ");
			this.getJdbcTemplate_newg().update(sb.toString());

			res.setRetCode(0);
			res.setRetMessage("OK");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return res;
		}
		
}
